import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    list: JSON.parse(localStorage.getItem('list') || '[]'),
    arr: ['全部', '已完成', '未完成'],
    isIndex: 0,
  },
  mutations: {
    // 添加
    add(state, text) {
      let id =
      state.list.length === 0 ? 100 : state.list[state.list.length - 1].id + 1;
      state.list.push( {
        id,
        name: text,
        isDone: false,
      })
    },
    // 是否选中
    isSelect(state, id) {
      const index = state.list.findIndex(item => item.id === id)
      state.list[index].isDone = !state.list[index].isDone
    },
    // 是否要全部  选择/不选择
    isAll(state, val) {
      state.list.filter(item => item.isDone = val)
    },
    // 删除
    del(state, id) {
      const index = state.list.findIndex(item => item.id === id)
      state.list.splice(index, 1)
    },
    // 判断底部选中状态
    check(state, index) {
      state.isIndex = index;
    },
    // 删除已选中
    delAll(state) {
      state.list = state.list.filter(item => !item.isDone)
    },
  },
  getters: {
    // 全选框是否选中
    getSlect(state) {
      if (state.list.length === 0) return false;
      return state.list.every(item => item.isDone);
    },
    // 底部判断影响主体信息
    isList(state) {
      if (state.arr[state.isIndex] === "已完成") {
        return state.list.filter((item) => item.isDone);
      }
      if (state.arr[state.isIndex] === "未完成")
        return state.list.filter((item) => !item.isDone);
      return state.list;
    },
  },
})

export default store